import { organizationAllFriends, organizationInfo } from '../../api/organization'
import { groupList } from '../../api/group'

const getDefaultState = () => {
  return {
    // 分组
    organizations: [],
    // 群组
    groups: [],
    // 好友
    friends: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_ORGANIZATIONS: (state, organizations) => {
    state.organizations = JSON.parse(JSON.stringify(organizations))
  },
  SET_GROUPS: (state, groups) => {
    state.groups = JSON.parse(JSON.stringify(groups))
  },
  SET_FRIENDS: (state, friends) => {
    state.friends = JSON.parse(JSON.stringify(friends))
  }
}

const actions = {
  // 设置分组
  async setOrganizations ({ commit, state }, { force = false } = { force: false }) {
    if (force || state.organizations.length === 0) {
      const { data } = await organizationInfo()
      commit('SET_ORGANIZATIONS', data)
    }
  },
  // 设置群组
  async setGroups ({ commit, state }, { force = false } = { force: false }) {
    if (force || state.groups.length === 0) {
      const { data } = await groupList()
      commit('SET_GROUPS', data)
    }
  },
  // 设置好友
  async setFriends ({ commit, state }, { force = false } = { force: false }) {
    if (force || state.friends.length === 0) {
      const { data } = await organizationAllFriends()
      commit('SET_FRIENDS', data)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
